$(function () {


    var allPage,page,cityName,lifeType,city,deptName,hospitalName,disPart,orderStatus,period,searchKey,size;


    // 获取城市列表...
    function getCityList() {
        // 从后台获取数据...
        $.ajax({
            async: false,
            cache:false,
            headers: {"Accept-CMS-Token":token},
            type: 'post',
            url: getareas,
            dataType: 'json',
            success: function (data) {

                if(data.resultCode==200) {
                    var list = data.value;
                    var len = list.length;

                    for( var i=0;i<len;i++ )
                    {
                        $('.getareas').append( '<option>'+list[i]+'</option>' );
                    };

                } else if(data.resultCode==515) {

                    reLogin();

                };
                console.log('获取地区成功...')
            },
            error: function () {
                console.log('获取地区失败...')
            }
        });

    };
    getCityList();

    // 获取城市对应的...医院列表
    function getHospitalList(cityName) {

        // 每次都把放医院的容器给清空...
        $('.hospital_list').html('');
        $('.hospital_list').append('<option value="">全部</option>');

        // 从后台获取数据...
        $.ajax({
            async: false,
            cache:false,
            headers: {"Accept-CMS-Token":token},
            type: 'post',
            url: getareashospital,
            dataType: 'json',
            data:{
                city:cityName
            },
            success: function (data) {

                if(data.resultCode==200) {
                    var list = data.value;
                    var len = list.length;

                    for( var i=0;i<len;i++ )
                    {
                        $('.hospital_list').append( '<option>'+list[i]+'</option>' );
                    };

                } else if(data.resultCode==515) {

                    reLogin();

                };
                console.log('获取医院成功...')
            },
            error: function () {
                console.log('获取医院失败...')
            }
        });

    };

    // 获取医院对应的...科室列表
    function getDepartmentList(cityName,hospitalName){

        // 每次都把放医院的容器给清空...
        $('.department_list').html('');
        $('.department_list').append('<option value="">全部</option>');

        // 从后台获取数据...
        $.ajax({
            async: false,
            cache:false,
            headers: {"Accept-CMS-Token":token},
            type: 'post',
            url: gethospitaloffice,
            dataType: 'json',
            data:{
                city:cityName,
                hospital:hospitalName
            },
            success: function (data) {

                if(data.resultCode==200) {
                    var list = data.value;
                    var len = list.length;

                    for( var i=0;i<len;i++ )
                    {
                        $('.department_list').append( '<option>'+list[i]+'</option>' );
                    };

                } else if(data.resultCode==515) {

                    reLogin();

                };
                console.log('获取科室成功...')
            },
            error: function () {

                console.log('获取科室失败...')

            }
        });

    }

    // 页面初始化...获取挂号订单列表...
    page = getRegistrationList( '','','','',false,'',1,'','',10 )
    getPage(page);
    exportOrder( '','','','','',1,'','',10 )


    // 获取挂号订单的列表....
    function getRegistrationList( lifeType,city,deptName,hospitalName,disPart,orderStatus,page,period,searchKey,size )
    {
        //清空表格当中的数据,并且追加表头
        clearTable();

        $.ajax({
            async: false,
            cache:false,
            headers: {"Accept-CMS-Token":token},
            type: 'post',
            url: factorquerylist,
            data: {
                lifeType:lifeType,
                city:city,
                deptName:deptName,
                hospitalName: hospitalName,
                disPart: disPart,
                orderStatus:orderStatus,
                page: page,
                period:period,
                queryStr:searchKey,
                size:size
            },
            dataType: 'json',
            success: successFn,
            error: function () {
                console.log('获取预约挂号订单列表获取失败...')
            }
        });

        return allPage;
    };

    //向后台请求参数,,,如果请求成功,,,就执行该函数,,,
    function successFn( data )
    {
        if(data.resultCode==200)
        {
            allPage = data.count;
            var value = data.value;
            var len = value.length;
            for( var i=0;i<len;i++)
            {
                $('.registration tbody').append('<tr id="'+value[i].id+'" user_id="'+value[i].user_id+'"></tr>');

                $('.registration tbody tr').eq(i).append('<td>'+(i+1)+'</td>');//序号

                $('.registration tbody tr').eq(i).append('<td>'+changeNull(value[i].order_no)+'</td>');//订单编号

                $('.registration tbody tr').eq(i).append('<td>'+changeNull(value[i].patient_name)+'</td>');//患者...

                $('.registration tbody tr').eq(i).append('<td>'+changeNull(value[i].hospital_name)+'</td>');//医院

                $('.registration tbody tr').eq(i).append('<td>'+changeNull(value[i].dept_name)+'</td>');//科室

                $('.registration tbody tr').eq(i).append('<td>'+changeNull(value[i].consultant_name)+'</td>');//医生

                $('.registration tbody tr').eq(i).append('<td>'+getClinicTime( Number(value[i].schedule_time + '000') )+'</td>');//就诊时间

                $('.registration tbody tr').eq(i).append('<td>'+changeClinicTime(value[i].period)+'</td>');//0是上午,1是下午,

                $('.registration tbody tr').eq(i).append('<td>'+changRegisOrderStatus(value[i].order_status,value[i].life_type)+'</td>');//订单状态

                $('.registration tbody tr').eq(i).append('<td><a href="#" class="look_registration">查看</a></td>');//操作


            };
        }
        else if(data.resultCode==515)
        {
            reLogin();
        }
        else
        {//这种状态下列表时没有数据
            $('.registration tbody').append('<tr><td></td><td></td><td>您搜索的内容不存在</td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>');
            hintUser();
            allPage = 1;
        }
    };

    // 当改变城市的时候...对应的医院后台获取...
    $('.getareas').change(function () {

        cityName = $('.getareas option:selected').html();

        if( cityName != '' ){

            getHospitalList(cityName);

            // 下面的列表的内容跟着变化
            city = changVoid( $('.getareas option:selected').html() );
            deptName = changVoid( $('.department_list option:selected').html() ) ;
            hospitalName = changVoid( $('.hospital_list option:selected').html() ) ;
            disPart = false;
            orderStatus = changVoid( $('.order_status option:selected').val() ) ;
            lifeType = getLifeType( orderStatus ) ;
            period = $('.clinic_time option:selected').val();
            searchKey = $('input[name = sou_registration_cont]').val().sTrim();
            size = 10;
            page = getRegistrationList( lifeType,city,deptName,hospitalName,disPart,orderStatus,1,period,searchKey,size );

            getPage(page);

            exportOrder( lifeType,city,deptName,hospitalName,orderStatus,page,period,searchKey,size )

        }else{

            // 每次都把放医院的容器给清空...
            $('.hospital_list').html('');
            $('.hospital_list').append('<option value="">全部</option>');

        }

    });

    // 当改变医院列表的时候...获取对应的科室
    $('.hospital_list').change(function () {

        cityName = $('.getareas option:selected').html();
        hospitalName = $('.hospital_list option:selected').html();

        if( hospitalName != '' ){

            getDepartmentList(cityName,hospitalName)

            // 下面的列表的内容跟着变化
            city = changVoid( $('.getareas option:selected').html() );
            deptName = changVoid( $('.department_list option:selected').html() ) ;
            hospitalName = changVoid( $('.hospital_list option:selected').html() ) ;
            disPart = false;
            orderStatus = changVoid( $('.order_status option:selected').val() ) ;
            lifeType = getLifeType( orderStatus ) ;
            period = $('.clinic_time option:selected').val();
            searchKey = $('input[name = sou_registration_cont]').val().sTrim();
            size = 10;
            page = getRegistrationList( lifeType,city,deptName,hospitalName,disPart,orderStatus,1,period,searchKey,size );

            getPage(page);

            exportOrder( lifeType,city,deptName,hospitalName,orderStatus,page,period,searchKey,size )

        }else{

            // 每次都把放医院的容器给清空...
            $('.department_list').html('');
            $('.department_list').append('<option value="">全部</option>');

        }

    });

    // 每一个下拉菜单发生变化的时候,,,,向后台请求,,,对应的列表发生变化;
    function changeXiaLa(x)
    {
        $(x).change(function (){
            city = changVoid( $('.getareas option:selected').html() );
            deptName = changVoid( $('.department_list option:selected').html() ) ;
            hospitalName = changVoid( $('.hospital_list option:selected').html() ) ;
            disPart = false;
            orderStatus = changVoid( $('.order_status option:selected').val() ) ;
            lifeType = getLifeType( orderStatus ) ;
            period = $('.clinic_time option:selected').val();
            searchKey = $('input[name = sou_registration_cont]').val();
            size = 10;
            page = getRegistrationList( lifeType,city,deptName,hospitalName,disPart,orderStatus,1,period,searchKey,size );

            getPage(page);

            exportOrder( lifeType,city,deptName,hospitalName,orderStatus,page,period,searchKey,size )

        });
    };
    changeXiaLa('.department_list');
    changeXiaLa('.clinic_time');
    changeXiaLa('.order_status');

    // 页面中的搜索功能
    $('.search_registration').click(function () {

        city = changVoid( $('.getareas option:selected').html() );
        deptName = changVoid( $('.department_list option:selected').html() ) ;
        hospitalName = changVoid( $('.hospital_list option:selected').html() ) ;
        disPart = false;
        orderStatus = changVoid( $('.order_status option:selected').val() ) ;
        lifeType = getLifeType( orderStatus ) ;
        period = $('.clinic_time option:selected').val();
        searchKey = $('input[name = sou_registration_cont]').val().sTrim();
        size = 10;
        page = getRegistrationList( lifeType,city,deptName,hospitalName,disPart,orderStatus,1,period,searchKey,size );

        getPage(page);

        exportOrder( lifeType,city,deptName,hospitalName,orderStatus,page,period,searchKey,size )

    });

    //当输入文本框中时,,,按下enter键,,,发起搜索,,,
    $(document).keydown(function(event){
        var ev = ev || event;

        if( ev.keyCode == 13 )
        {
            city = changVoid( $('.getareas option:selected').html() );
            deptName = changVoid( $('.department_list option:selected').html() ) ;
            hospitalName = changVoid( $('.hospital_list option:selected').html() ) ;
            disPart = false;
            orderStatus = changVoid( $('.order_status option:selected').val() ) ;
            lifeType = getLifeType( orderStatus ) ;
            period = $('.clinic_time option:selected').val();
            searchKey = $('input[name = sou_registration_cont]').val().sTrim();
            size = 10;
            page = getRegistrationList( lifeType,city,deptName,hospitalName,disPart,orderStatus,1,period,searchKey,size );

            getPage(page);

            exportOrder( lifeType,city,deptName,hospitalName,orderStatus,page,period,searchKey,size )
        };

    });

    // 点击查看...跳转到订单详情页...
    $(document).on('click','.look_registration',function () {

        var orderId = $(this).parent().parent().attr('id');
        var user_id = $(this).parent().parent().attr('user_id');

        window.location.href = look_registration + '?orderId=' + orderId + '&user_id=' + user_id;

    });

    // 将全部这两个字转化为空字符串...
    function changVoid(para) {

        if( para == '全部' ){
            return '';
        }else{
            return para;
        };

    };

    //分页插件的封装,方便多次调用
    function getPage(allPage)
    {
        $('.M-box2').pagination({
            pageCount:allPage,
            jump:true,
            coping:true,
            homePage:'首页',
            endPage:'末页',
            prevContent:'上页',
            nextContent:'下页',
            callback:function (api){//当点击页面当中的时候,会出发这个callback函数;;;;
                var page = api.getCurrent()+"";//得到的是要跳转到的那一页的页码;

                city = changVoid( $('.getareas option:selected').html() );
                deptName = changVoid( $('.department_list option:selected').html() ) ;
                hospitalName = changVoid( $('.hospital_list option:selected').html() ) ;
                disPart = false;
                orderStatus = changVoid( $('.order_status option:selected').val() ) ;
                lifeType = getLifeType( orderStatus ) ;
                period = $('.clinic_time option:selected').val();
                searchKey = $('input[name = sou_registration_cont]').val();
                size = 10;
                getRegistrationList( lifeType,city,deptName,hospitalName,disPart,orderStatus,page,period,searchKey,size );


            }
        });
    };
    getPage(allPage);

    //清空表格当中的数据,并且追加表头
    function clearTable()
    {
        $('.registration').html('');
        $('.registration').append('<thead><tr><th>序号</th><th>订单编号</th><th>患者</th><th>医院</th><th>科室</th><th>医生</th><th>就诊时间</th><th>上午/下午</th><th>订单状态</th><th>操作</th></tr></thead><tbody></tbody>');

    };

    // 根据后台返回的状态码...处理就诊时间段是上午还是下午
    function changeClinicTime(para)
    {
        if( para == null || para == '' ){

            return '';

        }else if( para == 0 ){

            return '上午'

        }else if( para == 1 ){

            return '下午'

        };
    };

    // 根据后台返回来的状态码...处理订单状态...
    function changRegisOrderStatus( para,life_type ) {

        if(life_type == 1){// 订单进行中

            // 进一步判断订单的状态...
            if( para == 1 ){

                return '抢号中'

            }else if( para == 2 ){

                return '未支付'

            }else if( para == 3 ){

                return '已支付'

            }else if( para == 4 ){

                return '已完成'

            };

        }else if(life_type == 2){//订单已完成

            return '已完成'

        }else if(life_type == 3){//订单已取消

            return '已取消'

        };


    };

    //将日期补0操作
    function getzf(num)
    {
        if(parseInt(num) < 10){
            num = '0'+num;
        }
        return num;
    };

    //将毫秒时间格式化为yyyy-MM-dd;处理就诊时间...
    function getClinicTime(str)
    {
        if(str != ''){

            var numStr = parseInt(str);

            var oDate = new Date(numStr),
                oYear=oDate.getFullYear(),
                oMonth = oDate.getMonth()+1,
                oDay = oDate.getDate(),
                oTime = getzf(oYear) +'-'+ getzf(oMonth) +'-'+ getzf(oDay);//最后拼接时间
            return oTime;

        }else{

            return '';

        };

    };

    // 封装一个函数...获取订单状态所对应的lifeType
    function getLifeType(para) {

        if(para == ''){//全部

            return '';

        }else if( para == 1 || para == 2 || para == 3){//订单进行中

            return 1;

        }else if(para == 4){//已完成

            return 2;

        }else if(para == 5){//已取消

            return 3;

        }

    }

    // 导出订单...按照搜索条件导出全部订单...
    function exportOrder( lifeType,city,deptName,hospitalName,orderStatus,page,period,searchKey,size )
    {
        //清空隐藏的表格的内容...并且追加表头...
        clearHideRegistrationTable('.registration_table');

        // 从后台获取到的数据都展示在隐藏的表格当中...
        $.ajax({
            async: false,
            cache:false,
            headers: {"Accept-CMS-Token":token},
            type: 'post',
            url: factorquerylist,
            data: {
                lifeType:lifeType,
                city:city,
                deptName:deptName,
                hospitalName: hospitalName,
                disPart: true,
                orderStatus:orderStatus,
                page: page,
                period:period,
                queryStr:searchKey,
                size:size
            },
            dataType: 'json',
            success: successExportFn,
            error: function () {
                console.log('获取预约挂号订单列表获取失败...')
            }
        });

    };

    // 请求导出的接口success后要执行的函数
    function successExportFn(data) {

        if(data.resultCode==200)
        {
            var value = data.value;
            var len = value.length;
            for( var i=0;i<len;i++)
            {
                $('.registration_table tbody').append('<tr id="'+value[i].id+'"></tr>');

                $('.registration_table tbody tr').eq(i).append('<td>'+(i+1)+'</td>');//序号

                $('.registration_table tbody tr').eq(i).append('<td style="vnd.ms-excel.numberformat:@;">'+changeNull(value[i].order_no)+'</td>');//订单编号

                $('.registration_table tbody tr').eq(i).append('<td>'+changeNull(value[i].patient_name)+'</td>');//患者...

                $('.registration_table tbody tr').eq(i).append('<td>'+changeNull(value[i].hospital_name)+'</td>');//医院

                $('.registration_table tbody tr').eq(i).append('<td>'+changeNull(value[i].dept_name)+'</td>');//科室

                $('.registration_table tbody tr').eq(i).append('<td>'+changeNull(value[i].consultant_name)+'</td>');//医生

                $('.registration_table tbody tr').eq(i).append('<td>'+getClinicTime( Number(value[i].schedule_time + '000') )+'</td>');//就诊时间

                $('.registration_table tbody tr').eq(i).append('<td>'+changeClinicTime(value[i].period)+'</td>');//0是上午,1是下午,

                $('.registration_table tbody tr').eq(i).append('<td>'+changRegisOrderStatus(value[i].order_status,value[i].life_type)+'</td>');//订单状态

            };
        }
        else if(data.resultCode==515)
        {
            reLogin();
        }
        else
        {//这种状态下列表时没有数据
            $('.registration_table tbody').append('<tr><td></td><td></td><td>亲,没有...</td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>');
        };

    }

    // 清空隐藏的表格
    function clearHideRegistrationTable(Dom) {
        $(Dom).html('');
        $(Dom).append('<thead><tr><th>序号</th><th>订单编号</th><th>患者</th><th>医院</th><th>科室</th><th>医生</th><th>就诊时间</th><th>上午/下午</th><th>订单状态</th></tr></thead><tbody></tbody>');

    };















});
